package QuizUI;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import QuizPackage.QuizDBC;

/**
 * Servlet implementation class InputQuiz
 */
@WebServlet("/InputQuiz")
public class InputQuiz extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InputQuiz() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//TODO Auto-generated method stub
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		QuizDBC dbc = new QuizDBC();
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		boolean random = request.getParameter("random")!=null;
		boolean singlepage = request.getParameter("singlepage")!=null;
		boolean correction = request.getParameter("correction")!=null;
		String category = request.getParameter("category");
		boolean practice = request.getParameter("practice")!=null;
		
		int quizID = dbc.addQuiz(name,(String)request.getSession().getAttribute("username"),random,singlepage,correction,description,category,practice);
		
		String tags = request.getParameter("tags");
		StringTokenizer tagTokens = new StringTokenizer(tags,",");
		while(tagTokens.hasMoreTokens()){
			String tag = tagTokens.nextToken();
			dbc.editTable("INSERT INTO tags VALUES("+quizID+",\""+tag+"\");");
		}
		
		request.setAttribute("quizid",quizID);
		
		RequestDispatcher dispatch = request.getRequestDispatcher("AddQuestion.jsp");
		dispatch.forward(request,response);
	}

}
